#!/usr/bin/python
'''
Created on Apr 22, 2011

@author: josh
'''
# python support
from threading import Thread
from time import sleep
import urllib2
import smtplib
import sys
import atexit , time
import os
import signal 
import ConfigParser
import socket

from email.mime.text import MIMEText

# application support
#from model import Profile

SAVE_OUT = None
SAVE_ERROR = None
PWD = None

class LoggerHead(object):
    '''
    Worker class to read logs and gather changes
    '''

    def __init__(self):
        '''
        Constructor
        '''
        self._url = None
        self._ll = None
        self._delay = None
        self._emails = None
        self._log = None
        self._run = False
        self._config()
        self._setup()
    
    def _setup(self):        
        try:
            f = open(self._ll)
            self._last = f.read()
            f.flush()
            f.close()
        except:
            self._last = "new"
        '''SAVE_OUT = sys.stdout
        sys.stdout = open('/var/log/loggerhead.log','w',0)
        SAVE_ERROR = sys.stderr
        sys.stderr = sys.stdout'''
    
    def _config(self):
        self._delay = 300   # every 30 minutes
        self._url = "http://slackware.osuosl.org/slackware64-current/ChangeLog.txt"
        self._ll = "./ll.log"
        self._emails = "jledford@synergies4u.com"
        PWD = os.getcwd()
        
        config = ConfigParser.RawConfigParser()
        
        if os.path.isfile('loggerhead.cfg'):
            config.read('loggerhead.cfg')
            self._emails = config.get('settings', 'email_list')
            self._ll = config.get('settings', 'll_filename')
            self._url = config.get('settings', 'slacklog_url')
            self._delay = config.get('settings', 'default_delay')
        else:
            config.add_section('settings')
            config.set('settings', 'email_list', self._emails)
            config.set('settings', 'll_filename', self._ll)
            config.set('settings', 'slacklog_url', self._url)
            config.set('settings', 'default_delay', self._delay)
            
            with open('loggerhead.cfg', 'wb') as configfile:
                config.write(configfile)
    
    def run(self):
        '''
        Threaded loop for running
        periodic log checks 
        '''
        # can not already be running!!!!
        if self._run:
            raise Exception("Already Running...")

        self._run = True
        
        # the loop
        while self._run:
            # open url
            try:
                rsp = urllib2.urlopen(self._url)
                print self._url
                line1 = rsp.readline()
                if line1 != self._last:
                    # create change object
                    lc = LogChange(line1, self._emails)
    
                    # read in all new lines
                    for line in rsp:
                        # break on match
                        if line == self._last:
                            break
                        
                        # add to change lost
                        lc.addLine(line)
                    
                    # fire notifications
                    lc.notify(self._last)
                    
                    # update log watch
                    self._last = line1
                    f = open(self._ll,"w+")
                    f.write(line1)
                    f.flush()
                    f.close()
                else:
                    print "No Change\n"
            except:
                print "Timed Out\n"
            sleep(float(self._delay))
            
    def stopPlease(self):
        self._run = False
    
    # Log Property 
    # (r/o property- use URL to set)
    def _getlog(self):
        return self._log
    log = property(_getlog)
    
    # delay property
    def _getdelay(self):
        return self._delay
    def _setdelay(self,secs):
        self._delay = secs
    
    delay = property(_getdelay,_setdelay)
     
class ChangeNotification(Thread):
    def __init__(self, lc, line1, emails):
        Thread.__init__(self)
        self._lc = lc
        self._ll = line1
        self._emails = emails
        
    def run(self):
        """
        First round, just send change listing 
        to all registered users.
        TODO: Be selective
        """
        # get change text
        chgtxt = self._lc.getChanges()
        self._send(self._emails,chgtxt)
        
    def _send(self, addr, txt):
        """
        send text to email addr
        """
        msg = MIMEText(txt)
        msg['Subject'] = 'Slackware Log Changes since  %s' % self._ll
        msg['From'] = "slacklog@synergies4u.com"
        msg['To'] = self._emails
        s = smtplib.SMTP('10.100.20.7',port=25)
        s.sendmail("slacklog@synergies4u.com", [self._emails], msg.as_string())
        s.quit()

        print msg
        
class LogChange(object):
    '''
    Captures and distributes log change
    '''
    def __init__(self, line1, emails):
        self._changetext = [line1]
        self._emails = emails
    
    def addLine(self,text):
        'Append text to changes'
        self._changetext.append(text)
        
    def notify(self, line1):
        """
        Send changes to all monitoring 
        emails.
        """
        cn = ChangeNotification(self,line1,self._emails)
        cn.start()
    
    def getChanges(self):
        return "".join(self._changetext)

def sigHupHandler(signum, frame):
    lh = LoggerHead()
    lh.stopPlease()
    lh._config()
    lh.run()
    
class Daemon:
    """
    A generic daemon class.
    
    Usage: subclass the Daemon class and override the run() method
    """
    
    def __init__(self, pidfile, pwd, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr
        self.pidfile = pidfile
        self.pwd = pwd
    
    def daemonize(self):
        """
        do the UNIX double-fork magic, see Stevens' "Advanced 
        Programming in the UNIX Environment" for details (ISBN 0201563177)
        http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
        """
        
        try: 
            pid = os.fork() 
            if pid > 0:
                # exit first parent
                sys.exit(0) 
        except OSError, e: 
            sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
            sys.exit(1)
    
        # decouple from parent environment
        os.chdir("/") 
        os.setsid() 
        os.umask(0) 
    
        # do second fork
        try: 
            pid = os.fork() 
            if pid > 0:
                # exit from second parent
                sys.exit(0) 
        except OSError, e: 
            sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
            sys.exit(1) 
    
        # redirect standard file descriptors
        '''sys.stdout.flush()
        sys.stderr.flush()
        si = file(self.stdin, 'r')
        so = file(self.stdout, 'a+')
        se = file(self.stderr, 'a+', 0)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())'''
    
        # write pidfile
        atexit.register(self.delpid)
        pid = str(os.getpid())
        os.chdir(self.pwd)
        file = open(self.pidfile,'w+',0)
        file.write("%s\n" % pid)
        file.flush()
        file.close()
    
    def delpid(self):
        os.remove(self.pidfile)

    def start(self):
        """
        Start the daemon
        """
        # Check for a pidfile to see if the daemon already runs
        try:
            pf = file(self.pidfile,'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None
    
        if pid:
            message = "pidfile %s already exist. Daemon already running?\n"
            sys.stderr.write(message % self.pidfile)
            sys.exit(1)
        
        # Start the daemon
        self.daemonize()
        self.run()

    def stop(self):
        """
        Stop the daemon
        """
        # Get the pid from the pidfile
        try:
            pf = file(self.pidfile,'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None
    
        if not pid:
            message = "pidfile %s does not exist. Daemon not running?\n"
            sys.stderr.write(message % self.pidfile)
            return # not an error in a restart

        # Try killing the daemon process    
        try:
            while 1:
                os.kill(pid, signal.SIGTERM)
                time.sleep(0.1)
        except OSError, err:
            err = str(err)
            if err.find("No such process") > 0:
                if os.path.exists(self.pidfile):
                    os.remove(self.pidfile)
            else:
                print str(err)
                sys.exit(1)

    def restart(self):
        """
        Restart the daemon
        """
        self.stop()
        self.start()
        
    def reload(self):
        os.chdir(self.pwd)
        try:
            pf = file(self.pidfile,'r')
            pid = int(pf.read().strip())
            pf.close()
            os.kill(pid, signal.SIGHUP)
            print "%s %s" % ("SIGHUP called to", pid)
        except:
            print "Not Running or Can't find PID"
        
    def run(self):
        lh = LoggerHead().run()

if __name__ == '__main__':
    # Do the Unix double-fork magic; see Stevens's book "Advanced
    # Programming in the UNIX Environment" (Addison-Wesley) for details
    signal.signal(signal.SIGHUP, sigHupHandler)
    pwd = os.getcwd()
    daemon = Daemon('loggerhead.pid', pwd)
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        elif 'reload' == sys.argv[1]:
            daemon.reload()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart|reload" % sys.argv[0]
        sys.exit(2)
    